# encoding=utf-8

import time
import urllib
import pandas as pd
from selenium import webdriver
from app.eastmoney.chaojiying import Chaojiying_Client

# // 卖出元素top_a


class eastmoneyDriver:

    def __init__(self):
        self.total = 0
        self.part = 10
        self.driver = webdriver.Chrome()
        # time.sleep(1)  # sleep一下，否则有可能报错
        self.driver.get("https://jy.xzsec.com/Login")
        # time.sleep(2)  # sleep一下，否则有可能报错
        self.autoLogin()


    def getDriver(self):
        return self.driver

    def autoLogin(self, username='', password=''):
        driver = self.driver
        elem_user = driver.find_element_by_xpath('//input[@id="txtZjzh"]')
        elem_user.send_keys(username)  # 浏览器版本不匹配的时候这里可能报错
        elem_pwd = driver.find_element_by_xpath('//input[@id="txtPwd"]')
        elem_pwd.send_keys(password)
        elem_verificode = driver.find_element_by_xpath('//input[@id="txtValidCode"]')
        imgurl = driver.find_element_by_xpath('//img[@id="imgValidCode"]').get_attribute('src')
        # 网络图片保存成本地图片
        urllib.request.urlretrieve(imgurl, 'D:/pychon/pycodes/app/eastmoney/YZM.jpg')
        chaojiying = Chaojiying_Client('wu2198', 'wu2198', '1f02b8a97bc4d6a9c56f80de3435e721')  # 用户中心>>软件ID 生成一个替换 96001
        im = open('D:/pychon/pycodes/app/eastmoney/YZM.jpg', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
        elem_verificode.send_keys(chaojiying.PostPic(im, 4004)['pic_str'])
        elem_time = driver.find_element_by_xpath('//input[@id="rdsc45"]')
        elem_time.click()
        elem_submit = driver.find_element_by_xpath('//button[@id="btnConfirm"]')
        elem_submit.click()  # 点击登录按钮
        time.sleep(0.8)
        return 0

    def close(self):
        self.driver.close()
        self.driver.quit()

    # 购买股票代码与数量,数量单位为股，且必须为100的整数倍
    def buy(self, codes, nums):
        if nums % 100 > 0:
            return 1
        driver = self.driver
        elem_user = driver.find_element_by_xpath('//li[@data-value="buy"]')
        elem_user.click()  # 切换到卖出页
        stockCode = driver.find_element_by_xpath('//input[@id="stockCode"]')
        stockCode.send_keys(codes)  # 填写股票代码
        stockCode.click()
        time.sleep(0.8)
        ver = driver.find_element_by_xpath('//div[@class="suggest-result"]/table/tbody/tr[1]')  # 点击下拉列表
        ver.click()
        iptcount = driver.find_element_by_xpath('//input[@id="iptCount"]')
        iptcount.click()
        iptcount.clear()
        iptcount.send_keys(nums)  # 填写购买数量
        time.sleep(3)
        button = driver.find_element_by_xpath('//button[@id="btnConfirm"]')
        button.click()  # 点击卖出按钮
        time.sleep(0.2)
        confirm = driver.find_element_by_xpath('//a[@data-role="confirm"]')
        confirm.click()  # 确认卖出
        return 0


    def sell(self, codes, nums):
        if nums % 100 > 0:
            return 1
        driver = self.driver
        elem_user = driver.find_element_by_xpath('//li[@data-value="sale"]')
        elem_user.click()  # 切换到卖出页
        stockCode = driver.find_element_by_xpath('//input[@id="stockCode"]')
        stockCode.send_keys(codes)  # 填写股票代码
        stockCode.click()
        time.sleep(0.8)
        ver = driver.find_element_by_xpath('//div[@class="suggest-result"]/table/tbody/tr[1]')  # 点击下拉列表
        ver.click()
        iptcount = driver.find_element_by_xpath('//input[@id="iptCount"]')
        iptcount.click()
        iptcount.clear()
        iptcount.send_keys(nums)  # 填写购买数量
        button = driver.find_element_by_xpath('//button[@id="btnConfirm"]')
        button.click()  # 点击卖出按钮
        time.sleep(1)
        confirm = driver.find_element_by_xpath('//a[@data-role="confirm"]')
        confirm.click()  # 确认卖出
        return 0

    # 获取已有的订单，即买了的所有的股票列表
    def getOnlinOrders(self):
        driver = self.driver
        driver.get('https://jy.xzsec.com/Search/Position')  # 切换资金及所有列表
        time.sleep(0.8)
        trs = driver.find_elements_by_xpath('//tbody[@id="tabBody"]/tr')
        lists = []
        for tr in trs:
            tds = tr.find_elements_by_tag_name('td')
            if not tds[2].text == '0':
                lists.append([tds[0].text, tds[1].text, tds[2].text, tds[3].text, tds[4].text, tds[5].text])
        df = pd.DataFrame(lists)
        df.columns = ['ts_code', 'name', 'allnum', 'available', 'costprice', 'price']
        return df

    # 获取所有可卖的订单，有些当天买的订单是不能卖的
    def getOnSellOrders(self):
        pass

    #  获取剩余资金量
    def getFundsInfo(self):
        driver = self.driver
        driver.get('https://jy.xzsec.com/Search/Position')  # 切换资金及所有列表
        time.sleep(0.8)
        spans = driver.find_elements_by_xpath('//span[@class="padl10"]/span')
        dic = {'total': spans[0].text, 'total': spans[1].text, 'total': spans[2].text, 'total': spans[3].text }
        return dic


    # 存储订单
    def saveOrders(self):
        pass

    #  更新所有的订单信息，即所有的表
    def updateOrderInfo(self):
        pass

    # 下单时平均分配每个订单使用的资金
    def distributeFunds(self):
        apart = 0
        available = self.total - self.part
        unit = available / (self.part - apart)

    #  自动下订单购买
    def autoBuy(self, code, price):
        dfunds = self.distributeFunds()
        num = dfunds - dfunds / price % 100  # 计算可买数量
        if self.buy(code, num):
            return True
        else:

            #   购买失败，需要撤单  这里面还需要考虑滑点的情况
            self.autoBuy(code, price + 0.01)

    #  自动卖出，止盈或者止损
    def autoSell(self, code):
    #     先获取数量
        num = 0
        pass

    #  撤单，撤销所有单子
    def revoke(self, code):
        self.driver.get('https://jy.xzsec.com/Trade/Revoke')




    def autoSell(self):
        pass





es = eastmoneyDriver()
print(es.getOnlinOrders())
# es.buy('300059', 100)
time.sleep(10000)
es.close()
